using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 一键写论文对话框
    /// </summary>
    public partial class PaperWritingDialog : Window
    {
        private readonly ILogger<PaperWritingDialog> _logger;
        private readonly IPaperWritingService _paperWritingService;
        private readonly IProjectService _projectService;
        private readonly IFileFormatService _fileFormatService;
        private readonly List<string> _selectedMaterialFiles = new();
        private CancellationTokenSource? _cancellationTokenSource;
        private bool _isGenerating = false;

        public Project? CurrentProject { get; set; }

        public PaperWritingDialog(IServiceProvider serviceProvider)
        {
            InitializeComponent();
            
            _logger = serviceProvider.GetRequiredService<ILogger<PaperWritingDialog>>();
            _paperWritingService = serviceProvider.GetRequiredService<IPaperWritingService>();
            _projectService = serviceProvider.GetRequiredService<IProjectService>();
            _fileFormatService = serviceProvider.GetRequiredService<IFileFormatService>();

            InitializeUI();
        }

        private void InitializeUI()
        {
            // 绑定滑块值变化事件
            CreativitySlider.ValueChanged += (s, e) =>
            {
                CreativityValueText.Text = e.NewValue.ToString("F1");
            };

            UpdateStatus("准备就绪", "Information", Brushes.Green);
        }

        /// <summary>
        /// 选择素材文件
        /// </summary>
        private void SelectMaterialFiles_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var openFileDialog = new OpenFileDialog
                {
                    Title = "选择论文参考素材文件",
                    Filter = "支持的文档|*.txt;*.docx;*.md|文本文件|*.txt|Word文档|*.docx|Markdown文件|*.md|所有文件|*.*",
                    Multiselect = true
                };

                if (openFileDialog.ShowDialog() == true)
                {
                    _selectedMaterialFiles.Clear();
                    _selectedMaterialFiles.AddRange(openFileDialog.FileNames);

                    // 更新界面显示
                    var fileNames = _selectedMaterialFiles.Select(Path.GetFileName);
                    MaterialFilesTextBox.Text = string.Join("\n", fileNames);
                    MaterialFilesCountText.Text = $"已选择 {_selectedMaterialFiles.Count} 个文件";

                    _logger.LogInformation($"用户选择了 {_selectedMaterialFiles.Count} 个素材文件");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "选择素材文件时发生错误");
                MessageBox.Show($"选择文件时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 开始生成论文
        /// </summary>
        private async void StartGeneration_Click(object sender, RoutedEventArgs e)
        {
            if (_isGenerating)
            {
                // 如果正在生成，则停止
                _cancellationTokenSource?.Cancel();
                return;
            }

            try
            {
                // 验证输入
                if (!ValidateInputs())
                {
                    return;
                }

                _isGenerating = true;
                _cancellationTokenSource = new CancellationTokenSource();
                
                // 更新UI状态
                StartButton.Content = "停止生成";
                StartButton.Background = Brushes.OrangeRed;
                UpdateStatus("正在生成论文...", "Loading", Brushes.Orange);

                // 构建论文生成请求
                var request = BuildPaperGenerationRequest();

                // 开始生成论文
                await GeneratePaperAsync(request, _cancellationTokenSource.Token);

                if (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    UpdateStatus("论文生成完成！", "CheckCircle", Brushes.Green);
                    MessageBox.Show("论文生成完成！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (OperationCanceledException)
            {
                UpdateStatus("生成已取消", "Cancel", Brushes.Gray);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成论文时发生错误");
                UpdateStatus("生成失败", "Error", Brushes.Red);
                MessageBox.Show($"生成论文时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isGenerating = false;
                StartButton.Content = "开始生成论文";
                StartButton.Background = SystemColors.ControlBrush;
            }
        }

        /// <summary>
        /// 验证输入参数
        /// </summary>
        private bool ValidateInputs()
        {
            if (_selectedMaterialFiles.Count == 0)
            {
                MessageBox.Show("请至少选择一个素材文件", "提示", 
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (!int.TryParse(TargetWordCountTextBox.Text, out int wordCount) || wordCount <= 0)
            {
                MessageBox.Show("请输入有效的目标字数", "提示", 
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 构建论文生成请求
        /// </summary>
        private PaperGenerationRequest BuildPaperGenerationRequest()
        {
            return new PaperGenerationRequest
            {
                Title = string.IsNullOrWhiteSpace(PaperTitleTextBox.Text) ? null : PaperTitleTextBox.Text,
                PaperType = ((ComboBoxItem)PaperTypeComboBox.SelectedItem).Content.ToString()!,
                Field = FieldTextBox.Text,
                TargetWordCount = int.Parse(TargetWordCountTextBox.Text),
                WritingStyle = ((ComboBoxItem)WritingStyleComboBox.SelectedItem).Content.ToString()!,
                CitationStyle = ((ComboBoxItem)CitationStyleComboBox.SelectedItem).Content.ToString()!,
                Creativity = (float)CreativitySlider.Value,
                MaterialFiles = _selectedMaterialFiles.ToList(),
                Structure = new PaperStructure
                {
                    IncludeAbstract = IncludeAbstractCheckBox.IsChecked == true,
                    IncludeKeywords = IncludeKeywordsCheckBox.IsChecked == true,
                    IncludeIntroduction = IncludeIntroductionCheckBox.IsChecked == true,
                    IncludeLiteratureReview = IncludeLiteratureReviewCheckBox.IsChecked == true,
                    IncludeMethodology = IncludeMethodologyCheckBox.IsChecked == true,
                    IncludeResults = IncludeResultsCheckBox.IsChecked == true,
                    IncludeDiscussion = IncludeDiscussionCheckBox.IsChecked == true,
                    IncludeConclusion = IncludeConclusionCheckBox.IsChecked == true,
                    IncludeReferences = IncludeReferencesCheckBox.IsChecked == true
                },
                OutputFormat = GetSelectedOutputFormat(),
                SaveToProject = SaveToProjectCheckBox.IsChecked == true,
                UserRequirements = string.IsNullOrWhiteSpace(UserRequirementsTextBox.Text) ? null : UserRequirementsTextBox.Text
            };
        }

        /// <summary>
        /// 获取选择的输出格式
        /// </summary>
        private string GetSelectedOutputFormat()
        {
            var selectedItem = (ComboBoxItem)OutputFormatComboBox.SelectedItem;
            var content = selectedItem.Content.ToString()!;
            
            if (content.Contains(".docx")) return "docx";
            if (content.Contains(".txt")) return "txt";
            if (content.Contains(".md")) return "md";
            
            return "docx"; // 默认格式
        }

        /// <summary>
        /// 生成论文
        /// </summary>
        private async Task GeneratePaperAsync(PaperGenerationRequest request, CancellationToken cancellationToken)
        {
            try
            {
                // 设置进度回调
                var progress = new Progress<string>(message =>
                {
                    Dispatcher.Invoke(() => UpdateStatus(message, "Loading", Brushes.Orange));
                });

                // 调用论文写作服务
                var result = await _paperWritingService.GeneratePaperAsync(request, progress, cancellationToken);

                if (result.IsSuccess && !string.IsNullOrEmpty(result.Content))
                {
                    // 保存论文
                    await SavePaperAsync(result, request);
                }
                else
                {
                    throw new Exception(result.ErrorMessage ?? "生成论文失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成论文过程中发生错误");
                throw;
            }
        }

        /// <summary>
        /// 保存论文
        /// </summary>
        private async Task SavePaperAsync(PaperGenerationResult result, PaperGenerationRequest request)
        {
            try
            {
                string fileName = $"{result.Title ?? "论文"}_{DateTime.Now:yyyyMMdd_HHmmss}.{request.OutputFormat}";
                string filePath;

                if (request.SaveToProject && CurrentProject != null)
                {
                    // 保存到项目文件夹
                    var paperFolder = Path.Combine(CurrentProject.RootPath, "论文");
                    Directory.CreateDirectory(paperFolder);
                    filePath = Path.Combine(paperFolder, fileName);
                }
                else
                {
                    // 让用户选择保存位置
                    var saveFileDialog = new SaveFileDialog
                    {
                        FileName = fileName,
                        Filter = GetSaveFileFilter(request.OutputFormat),
                        DefaultExt = request.OutputFormat
                    };

                    if (saveFileDialog.ShowDialog() != true)
                    {
                        return;
                    }

                    filePath = saveFileDialog.FileName;
                }

                // 根据格式保存文件
                var fileFormat = GetFileFormat(request.OutputFormat);
                await _fileFormatService.SaveContentAsync(filePath, result.Content, fileFormat);

                _logger.LogInformation($"论文已保存到: {filePath}");
                UpdateStatus($"论文已保存: {Path.GetFileName(filePath)}", "CheckCircle", Brushes.Green);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存论文时发生错误");
                throw new Exception($"保存论文失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取保存文件对话框的过滤器
        /// </summary>
        private string GetSaveFileFilter(string format)
        {
            return format.ToLower() switch
            {
                "docx" => "Word文档|*.docx",
                "txt" => "文本文件|*.txt",
                "md" => "Markdown文件|*.md",
                _ => "所有文件|*.*"
            };
        }

        /// <summary>
        /// 获取文件格式枚举
        /// </summary>
        private Services.FileFormat GetFileFormat(string format)
        {
            return format.ToLower() switch
            {
                "docx" => Services.FileFormat.Docx,
                "txt" => Services.FileFormat.Text,
                "md" => Services.FileFormat.Markdown,
                _ => Services.FileFormat.Text
            };
        }

        /// <summary>
        /// 更新状态显示
        /// </summary>
        private void UpdateStatus(string message, string iconKind, Brush color)
        {
            StatusText.Text = message;
            StatusText.Foreground = color;
            // 这里可以根据iconKind设置不同的图标
        }

        /// <summary>
        /// 取消按钮
        /// </summary>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            if (_isGenerating)
            {
                _cancellationTokenSource?.Cancel();
            }
            
            Close();
        }
    }
}
